var amapKey="a0913e92907bdd4150e564d6439c8466";

var UIOPTIONS={
    HeaderWithCart:false,
    HeaderWithBack:true,
    HeaderWithShare:false
}

var CART_BTN=null;

var mylocation={lat: 31.1189,lng:121.581}

var CITIES={"北京":["西城","东城","崇文","宣武","朝阳","海淀","丰台","石景山","门头沟","房山","通州","顺义","大兴","昌平","平谷","怀柔","密云","延庆"],"天津":["青羊","河东","河西","南开","河北","红桥","塘沽","汉沽","大港","东丽","西青","北辰","津南","武清","宝坻","静海","宁河","蓟县","开发区"],"河北":["石家庄","秦皇岛","廊坊","保定","邯郸","唐山","邢台","衡水","张家口","承德","沧州","衡水"],"山西":["太原","大同","长治","晋中","阳泉","朔州","运城","临汾"],"内蒙古":["呼和浩特","赤峰","通辽","锡林郭勒","兴安"],"辽宁":["大连","沈阳","鞍山","抚顺","营口","锦州","丹东","朝阳","辽阳","阜新","铁岭","盘锦","本溪","葫芦岛"],"吉林":["长春","吉林","四平","辽源","通化","延吉","白城","辽源","松原","临江","珲春"],"黑龙江":["哈尔滨","齐齐哈尔","大庆","牡丹江","鹤岗","佳木斯","绥化"],"上海":["浦东","杨浦","徐汇","静安","卢湾","黄浦","普陀","闸北","虹口","长宁","宝山","闵行","嘉定","金山","松江","青浦","崇明","奉贤","南汇"],"江苏":["南京","苏州","无锡","常州","扬州","徐州","南通","镇江","泰州","淮安","连云港","宿迁","盐城","淮阴","沐阳","张家港"],"浙江":["杭州","金华","宁波","温州","嘉兴","绍兴","丽水","湖州","台州","舟山","衢州"],"安徽":["合肥","马鞍山","蚌埠","黄山","芜湖","淮南","铜陵","阜阳","宣城","安庆"],"福建":["福州","厦门","泉州","漳州","南平","龙岩","莆田","三明","宁德"],"江西":["南昌","景德镇","上饶","萍乡","九江","吉安","宜春","鹰潭","新余","赣州"],"山东":["青岛","济南","淄博","烟台","泰安","临沂","日照","德州","威海","东营","荷泽","济宁","潍坊","枣庄","聊城"],"河南":["郑州","洛阳","开封","平顶山","濮阳","安阳","许昌","南阳","信阳","周口","新乡","焦作","三门峡","商丘"],"湖北":["武汉","襄樊","孝感","十堰","荆州","黄石","宜昌","黄冈","恩施","鄂州","江汉","随枣","荆沙","咸宁"],"湖南":["长沙","湘潭","岳阳","株洲","怀化","永州","益阳","张家界","常德","衡阳","湘西","邵阳","娄底","郴州"],"广东":["广州","深圳","东莞","佛山","珠海","汕头","韶关","江门","梅州","揭阳","中山","河源","惠州","茂名","湛江","阳江","潮州","云浮","汕尾","潮阳","肇庆","顺德","清远"],"广西":["南宁","桂林","柳州","梧州","来宾","贵港","玉林","贺州"],"海南":["海口","三亚"],"重庆":["渝中","大渡口","江北","沙坪坝","九龙坡","南岸","北碚","万盛","双桥","渝北","巴南","万州","涪陵","黔江","长寿"],"四川":["成都","达州","南充","乐山","绵阳","德阳","内江","遂宁","宜宾","巴中","自贡","康定","攀枝花"],"贵州":["贵阳","遵义","安顺","黔西南","都匀"],"云南":["昆明","丽江","昭通","玉溪","临沧","文山","红河","楚雄","大理"],"西藏":["拉萨","林芝","日喀则","昌都"],"陕西":["西安","咸阳","延安","汉中","榆林","商南","略阳","宜君","麟游","白河"],"甘肃":["兰州","金昌","天水","武威","张掖","平凉","酒泉"],"青海":["黄南","海南","西宁","海东","海西","海北","果洛","玉树"],"宁夏":["银川","吴忠"],"新疆":["乌鲁木齐","哈密","喀什","巴音郭楞","昌吉","伊犁","阿勒泰","克拉玛依","博尔塔拉"],"香港":["中西区","湾仔区","东区","南区","九龙-油尖旺区","九龙-深水埗区","九龙-九龙城区","九龙-黄大仙区","九龙-观塘区","新界-北区","新界-大埔区","新界-沙田区","新界-西贡区","新界-荃湾区","新界-屯门区","新界-元朗区","新界-葵青区","新界-离岛区"],"澳门":["花地玛堂区","圣安多尼堂区","大堂区","望德堂区","风顺堂区","嘉模堂区","圣方济各堂区","路氹城"]};

var Wrap = React.createClass({
    onLogin:function(data){
        //console.log(data);
        var customer=data.customer;
        var customerId=qs.uid||$.cookie('uid')||customer.id;
        this.setState({customerId:customerId,customer:customer});
    },
    getInitialState: function() {
            return {customerId:this.props.customerId};
    },
    componentDidMount: function() {
            console.log('mounted wrap');
            var customerId=this.props.customerId;
            if(customerId){
                API.customerGet({customerId:customerId},function(customer){
                    this.setState({customerId:customerId,customer:customer});
                }.bind(this));
            }
        },
    render: function(){
        var customer=this.state.customer||{};
        var customerId=this.state.customerId||customer.id;
        var content=React.Children.map(this.props.children, function(c){
            c.props.customer=customer;
            c.props.customerId=c.props.customerId||this.state.customerId||customer.id;
            return c;
         }.bind(this));
        return (
<div id="wrapper">
    <NavBar {...this.props} customer={customer} customerId={customerId} />
    <div id="page-content-wrapper">
        <div className="container-fluid">
            <ToggleMenu customerId={customerId}/>
            <div id="mallBody">
                {this.props.children}
            </div>
        </div>
        <LoginModal onLogin={this.onLogin.bind(this)}/>
        
    </div>
</div>
         );
    }
});


var ToggleMenu = React.createClass({
    toggleMenu: function(e){
        e.preventDefault();
        $("#wrapper").toggleClass("toggled");
        $("#menu-toggle").toggleClass("toggled");
    },
    openShare:function(){
        wx.showMenuItems({
            menuList: ["menuItem:share:appMessage", "menuItem:share:timeline","menuItem:share:qq","menuItem:share:weiboApp"]
        });
    },
    handleBack:function(){
        history.back();
    },
    render:function(){
        var rightBtn=null
        if(this.props.withcart||UIOPTIONS.HeaderWithCart){
          rightBtn=<CartToggle customerId={this.props.customerId} onClick={function(){toPage('CartPage')}.bind(this)}/>;
        }else if(this.props.withback||UIOPTIONS.HeaderWithBack){
          rightBtn=<button className="btn btn-primary" onClick={function(){history.back()}}><span className="icon back" /></button>
        }
        return (
        <div className="navbar bg-primary hidden-print navbar-static-top">
            <div id="menu-toggle" className="pull-left" onClick={this.toggleMenu}>
            <button type="button" className="btn btn-primary">
               <span className="icon menu" />
             </button>
            </div>
            <div className="pull-right">
              {rightBtn}
            </div>
        </div>);
    }
})

var CartToggle = React.createClass({
  getInitialState: function() {
        return {cart:this.props.cart||{}}
  },
  componentDidMount: function() {
    if(!this.props.cart){
      API.customerCart({customerId:this.props.customerId},function(data){
          this.setState({cart:data});
      }.bind(this))
    }
    CART_BTN=this;
  },
  render:function(){
    var cart=this.state.cart||{}
    var count=cart.itemCount||0
    return (<button onClick={function(){toPage('CartPage',{customerId:customerId},'/#cart')}.bind(this)} className="btn btn-primary btn-lg" type="button">
          <span className="glyphicon glyphicon-check"/> <span className="badge">{count}</span>
        </button>);
  }
})


var AdItem = React.createClass({
    render:function(){
        var ad=this.props.advertisement||{}
        var picture=ad.picture?'/api/thumb/'+ad.picture+'/512/512':"http://cdn.fruitday.com/images/2015-05-21/1432190870_pic.jpg";
        if(ad.level==1){
            picture=ad.picture?'/api/thumb/'+ad.picture+'/512/0':"http://cdn.fruitday.com/images/2015-05-21/1432190870_pic.jpg";
        }
        if(ad.refProduct){
          return (<div className="col-xs-6 grid-item">
            <a href="javascript:;" onClick={toPage.bind(this,'ProductDetailPage',{id:ad.refProduct.id},null)} >
            <img className="img-responsive img-rounded" src={picture}/>
            </a>
            </div>)
        }else if(ad.url){
          return (<div className="col-xs-6 grid-item">
            <a href={ad.url}>
            <img className="img-responsive img-rounded" src={picture}/>
            </a>
            </div>)
        }
        
    }
});

var AdList = React.createClass({
  componentDidMount: function() {
    $.get('/api/advertisements',{level:this.props.level||1},function(data){
      this.setState({advertisements:data.content})
    }.bind(this))
  },
  getInitialState: function() {
    return {
      advertisements:[]
    };
  },
  render:function(){
    if((this.props.level||1)==1){
      var items = this.state.advertisements.map(function(ad){
        return {src:'/api/thumb/'+ad.picture+'/0/0'}
      })
      if(items.length>0)
        items[0].active=true;
      return <Slider items={items}/>
    }else{
      var items = this.state.advertisements.map(function(ad){
        return <AdItem advertisement={ad} />
      })
      return (<div>{items}</div>)
    }
    
  }
})


var NavBar = React.createClass({
  render:function(){
    return (<div/>);
  }
})

var LoginModal = React.createClass({
    render:function(){
      var title=this.props.title||"用户登录";
      return (<Modal title={title} id="loginModal" onLogin={this.props.onLogin}><LoginPage/></Modal>)
    }
})

var LoginPage = React.createClass({
    handleLogin:function(){
        API.customerLogin($('form',this.getDOMNode()).serialize(),function(data){
            //console.log(data);
            $(this.getDOMNode()).modal('hide');
            if(this.props.onLogin){
                this.props.onLogin(data);
            }else{
              history.back()
            }
        }.bind(this));
    },
    componentDidMount: function(){
        if(this.props.show){
            $(this.getDOMNode()).modal('show');
        }
    },
    render:function(){
        
        return (

          <div className="panel-body">
            <form action="/api/users/login" method="post">
                <h3>用户登录</h3>
                <div className="input-group">
                  <span className="input-group-addon">用户名：</span>
                  <input name="username" type="text" className="form-control" placeholder="手机号／用户名"/>
                </div>
                <div className="input-group">
                  <span className="input-group-addon">密码：</span>
                  <input name="password" type="password" className="form-control" placeholder="长度不少于6位的字母或数字"/>
                </div>
            </form>
            <div role="presentation" className="divider"></div>
            <div  className="input-group col-xs-12">
                <button onClick={this.handleLogin.bind(this)} className="btn btn-primary btn-lg col-xs-12">登录</button>
            </div>
        </div>);
    }
});

 var UserBadge = React.createClass({
   render: function() {
     var customer=this.props.customer||{};
     return (
       <div className="UserBadge">
         <div className="">
           <img className="avatar" src={customer.avatar?'/api/thumb/'+customer.avatar+'/64/64':'/img/avatar_default.jpg'} />
         </div>
         <div className="UserTitle">{customer.loginname}</div>
       </div>
     );
   }
 });

 var DatePicker = React.createClass({
     componentDidMount: function() {
        var format=this.props.format||'YYYY-MM-DD HH:mm:00';
        var initialDate=this.props.defaultValue?new Date(this.props.defaultValue):new Date()
        var domNode=$(this.getDOMNode()).datetimepicker({format: format,inline:true,sideBySide:true,stepping:10,keepOpen:true,defaultDate:this.props.defaultDate||new Date()});
        if(this.props.min){
          domNode.data("DateTimePicker").minDate(this.props.min);
        }

        if(this.props.max){
          domNode.data("DateTimePicker").maxDate(this.props.max);
        }
     },
     render: function() {
       var customer=this.props.customer||{};
       return (
         <input {...this.props} type='text' className="form-control"/>
       );
     }
});

var LinkedDatePicker = React.createClass({
    handleStartChange:function(e){
      console.log(e.target)
    },
    getInitialState: function() {
      return {
        start:this.props.start||new Date(),end:this.props.end||new Date(new Date().getTime()+7200000)
      };
    },
    componentDidMount: function() {
      var startNode=$('#likedDate_Start',this.getDOMNode())
      var endNode=$('#likedDate_End',this.getDOMNode())
      startNode.on("dp.change", function (e) {
          endNode.data("DateTimePicker").minDate(e.date);
      });
      endNode.on("dp.change", function (e) {
          startNode.data("DateTimePicker").maxDate(e.date);
      });
    },
    render: function() {
     var customer=this.props.customer||{};
     return (
      <div>
       <DatePicker id="likedDate_Start" name={this.props.nameStart||"_startDate"} defaultDate={this.state.start} onChange={this.handleStartChange}/>
       <DatePicker id="likedDate_End" name={this.props.nameEnd||"_endDate"} defaultDate={this.state.end} />
      </div>
     );
    }
});

var Modal = React.createClass({

      render: function() {
        return (
          <div className="modal" {...this.props}>
            <div className="modal-dialog">
              <div className="modal-content">
                <div className="modal-header">
                  <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span className="glyphicon glyphicon-remove"></span></button>
                  <h4 className="modal-title">{this.props.title}</h4>
                </div>
                <div className="modal-body">
                  {this.props.children}
                </div>
                <div className="modal-footer">
                </div>
              </div>
            </div>
          </div>
        );
      }
 });

var ConfirmBox = React.createClass({
  render:function(){

    return (<div  className="modal">
      <div className="modal-dialog modal-sm">
        <div className="modal-content">
          <div className="modal-header">
            <button type="button" className="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
            <h5 className="modal-title"><i className="fa fa-exclamation-circle"></i> {this.props.title}</h5>
          </div>
          <div className="modal-body small">
            <p>{this.props.message}</p>
          </div>
          <div className="modal-footer" >
            <button type="button" className="btn btn-primary ok" data-dismiss="modal" onClick={this.props.onOK}>{this.props.ok||'确定'}</button>
            <button type="button" className="btn btn-default cancel" data-dismiss="modal" onClick={this.props.onCancel}>{this.props.cancel||'取消'}</button>
          </div>
        </div>
      </div>
    </div>)
  }
});

 var LocationPicker = React.createClass({
    handleAddressChanged: function(){
        var thisElement=this.getDOMNode();
        var addr=$('.city',thisElement).val()+$('.street',thisElement).val();
        geolocation(addr,function(data){
            var poiArr = data.poiList.pois;
            if(poiArr.length>0){
                var d=poiArr[0];
                var loc=d.location;
                $('.lat',thisElement).val(d.location.getLat());
                $('.lng',thisElement).val(d.location.getLng());
            }else{
                $('.street',thisElement).val('');
            }

        });
    },
    render: function(){
        var address=this.props.address||{}
        var location=this.props.location||{}
        return (
        <div>
            <CitySelector address={address} inline={true}/>
            <div className="input-group">
                <span className="input-group-addon">街道：</span>
                <input name="address_street" defaultValue={address.street} className="form-control street" onChange={this.handleAddressChanged}/>
            </div>
            <div className="input-group">
              <span className="input-group-addon">坐标：</span>
              <input name="location_lat" defaultValue={location.lat} readOnly className="form-control lat"/>
              <input name="location_lng" defaultValue={location.lng} readOnly className="form-control lng"/>
            </div>
        </div>
        );
    }
 })

var CitySelector = React.createClass({
  handleProviceChange:function(e){
    this.setState({province:$(e.target).val()})
  },
  getInitialState:function(){
    var address=this.props.address||{}
    return ({province:address.province||'上海',city:address.city||''});
  },
  componentDidMount:function(){
    //if(this.props.onChange)
      //this.props.onChange({target:$('select.city',this.getDOMNode())})
  },
  render:function(){
    var provinceOptions=[];
    var address=this.props.address||{}
    for (province in CITIES){
      if(province==this.state.province){
        provinceOptions.push (<option value={province} selected>{province}</option>)
      }else{
        provinceOptions.push (<option value={province} >{province}</option>)
      }
    }
    var width=this.props.inline?"50%":"100%"
    var cityOptions=CITIES[this.state.province].map(function(city){
                return (<option value={city}>{city}</option>);
            });
    return (<div className="input-group">
              <span className="input-group-addon">城市：</span>
              <select name="address_province" style={{width:width}} defaultValue={this.state.province} className="form-control province" onChange={this.handleProviceChange}>
                  {provinceOptions}
              </select>
              <select name="address_city" onChange={this.props.onChange} style={{width:width}} className="form-control city">
                  {cityOptions}
              </select>
            </div>)
  }
})

var NumberSelector = React.createClass({
    handleClick: function(v){
        var nv=this.state.value+v;
        var min=this.props.min||0;
        if(nv>=min){
            if(this.props.onChange){
                if(!this.props.onChange(nv)){
                    this.setState({value:nv});
                }
            }else{
                this.setState({value:nv});
            }

        }
    },
    getInitialState: function() {
        return {value:this.props.value||0};
    },
    componentDidMount:function(){
      this.handleClick(1);
    },
    render: function(){
        return (<div className="input-group">
              <span className="input-group-addon">{this.props.label}</span>
              <span className="input-group-btn">
                <button className="btn btn-success" onClick={this.handleClick.bind(this,1)}>&nbsp;+&nbsp;</button>
              </span>
              <input className="form-control" readOnly name={this.props.name} value={this.state.value}/>
              <span className="input-group-btn">
                  <button className="btn btn-success" onClick={this.handleClick.bind(this,-1)}>&nbsp;-&nbsp;</button>
                </span>
        </div>
        );
    }
})

var AjaxLoad = React.createClass({
    componentDidMount:function(){
        console.log('mounted');
        var e=this.getDOMNode()
        $(document).ajaxStart(function(){
            console.log('loading');
            $(e).modal("show");
        }).ajaxStop(function(){
            console.log('done');
            $(e).modal("hide");
            $('.modal-backdrop').hide();
        });
    },
    render:function(){
        return (<Modal id="loadingModal">loading</Modal>)
    }
})

var Slider = React.createClass({
    render:function(){
      var i=0;
      var itemOls=this.props.items.map(function(item){
        var clsName=item.active?"active":"normal";
        i++;
        return(<li data-target="#carousel-slide" data-slide-to={i-1} className={clsName}></li>)
      })

      var itemBody=this.props.items.map(function(item){
        var clsName=item.active?"item active":"item";
        return(<div className={clsName} alt={item.index}>
            <img src={item.src} alt={item.alt}/>
            <div className="carousel-caption">
              {item.caption}
            </div>
          </div>);
      })

      return (<div id="carousel-slide" className="carousel slide" data-ride="carousel">
  <ol className="carousel-indicators">
    {itemOls}
  </ol>

  <div className="carousel-inner" role="listbox">
    {itemBody}
  </div>

  
</div>
        )
    }
})


var FileUploader=React.createClass({
  onUploaded:function(event,data){
    var form = data.form, files = data.files, extra = data.extra, 
        response = data.response, reader = data.reader;
    alert('文件上传成功');
    console.log(response)
    if(this.props.onUploaded){
      console.log(response.filename)
      this.props.onUploaded(response.filename);
    }
  },
  componentDidMount:function(){
    var thisElement=this.getDOMNode();
    var initialPreview=this.props.picture?"<img src='/api/thumb/"+this.props.picture+"/256/256'/>":"";
    //filebatchuploadsuccess
    this.domNode=$('.fileinput',thisElement).fileinput({initialPreview:initialPreview,previewFileType: "image",uploadAsync:true,language: "zh",uploadUrl: "/api/attachments"}).on('fileuploaded', this.onUploaded.bind(this));
  },
  render:function(){
    var initialPreview=this.props.picture?"<img src='/api/thumb/"+this.props.picture+"/256/256'/>":"";
    if(this.domNode)
      this.domNode.fileinput('refresh',{initialPreview:initialPreview}).on('fileuploaded', this.onUploaded.bind(this));
    return(<div>
      <input name="file" type="file" accept="image/*" className="fileinput form-control" />
    </div>)
    
  }
})

var ContentEditable = React.createClass({
    render: function(){
        return <div className="editable form-control"
            onBlur={this.emitChange}
            contentEditable >{this.props.children}</div>
    },

    shouldComponentUpdate: function(nextProps){
        return nextProps.html !== this.getDOMNode().innerHTML;
    },

    componentDidUpdate: function() {
        if ( this.props.html !== this.getDOMNode().innerHTML ) {
           this.getDOMNode().innerHTML = this.props.html;
        }
    },

    emitChange: function(){
        var html = this.getDOMNode().innerHTML;
        if (this.props.onChange && html !== this.lastHtml) {
            this.props.onChange({
                target: {
                    value: html
                }
            });
        }
        this.lastHtml = html;
    }
});

// function loadPage(page){
//     React.render(page, $('#list').get(0));
// }

function loadPage(element,props,url){
  if(!element){
    var hash=document.location.hash
    if(hash.length>1){
      var hArr=hash.substring(1).split("?");
      element = hArr[0].substring(1);
      props = hArr.length>1?query2props(hArr[1]):{};
    }
  }

  history.replaceState({element:element||"HomePage",props:props||{}},"",url);
  mountElement(element||"HomePage",props||{})
    
    //API.wxConfig();
}



var query2props = function(sPageURL){
    var
    i = 0,
    retObj = {},
    pair = null,
    qArr = sPageURL.split('&');
 
    for (; i<qArr.length; i++){
        pair = qArr[i].split('=');
        retObj[pair[0]] = pair[1];
    };
 
    return retObj;
}

function props2query(props){
  var str=""
  for(var k in props){
    str+=k+"="+props[k]+"&"
  }
  return str;
}

function toPage(element,props,url){
    var props=props||{};
    if(!url){
      url="/main.html#/"+element+"?"+$.param(props);
    }
    history.pushState({element:element,props:props},"",url);
    mountElement(element,props)
    //API.wxConfig();
}

function mountElement(element,props){
    var e=React.createElement(eval(element), props);
    //if(customerId)
      //e=React.createElement(Wrap,{customerId:customerId},e);
    React.unmountComponentAtNode($('#mallBody').get(0));
    React.render(e,$('#mallBody').get(0));

}

window.addEventListener("popstate", function() {
    var currentState = history.state;
    if(currentState&&currentState.element){
        mountElement(currentState.element,currentState.props);
    }else{
        document.location.href=document.location.href;
    }
});


